from sqlalchemy import Column, String, create_engine, Integer, Float, Date, MetaData, TEXT, event
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.pool import NullPool
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import text


Base = declarative_base()
metadata = MetaData()
class JslUserInfo(Base):
    # 表的名字:
    __tablename__ = 'jsl_user_info'

    # 表的结构:
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(255))
    kbzw__Session = Column(String(255))
    kbzw_r_uname = Column(String(255))
    kbzw__user_login = Column(String(255))
    
class DbHandler(object):
    def __init__(self, name='lhjy'):
        con_url = 'mysql+pymysql://root:alpine123@localhost:3306/' + name
        self.db_addr = con_url
        # self.connect = None
        # self.session = None
        # self.engine = None

    def create_session(self):
        self.engine = create_engine(self.db_addr, poolclass=NullPool)
        self.session = scoped_session(sessionmaker(bind=self.engine))
        self.connect = self.engine.connect()

    def close_session(self):
        self.session.close()
        self.connect.close()

class MySQLStorage(DbHandler):
    def __init__(self, name='lhjy'):
        super().__init__(name)
        self.create_session()

    def save(self, data):
        # 这里需要根据数据结构和表结构来实现具体的保存逻辑
        pass

    def query_all(self):
        sql = text("SELECT * FROM JSL_bonds_alive")
        results = self.connect.execute(sql)
        return [dict(row) for row in results]

    def __del__(self):
        self.close_session()